/* $RCSFile: PortalSettingsDictionary.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Configuration/Settings/PortalSettingsDictionary.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:27  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Settings;

using Path2     =   AddonNice.Settings.Path;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;
using Key2      =   AddonNice.Settings.Cache.Key;

namespace AddonNice.Configuration
{

    /// <summary>
    /// Dedicated dictionary for module settings
    /// </summary>
    public class PortalSettingsDictionary : SettingsDictionary
    {
		#region This delegate is created to manage Portal Extensions CS dec 2004

		public static event PortalSettingsCreatedEventHandler PortalSettingsCreatedEvent;

		public void OnPortalSettingsCreated(PortalSettingsCreatedEventArgs e) 
		{
            if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary OnPortalSettingsCreated BEG count: {0}.",e.BaseSettings.Count),SettingsTraceSwitch.Sw.Info);
			if ( PortalSettingsCreatedEvent != null )
				PortalSettingsCreatedEvent(e);
            if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary OnPortalSettingsCreated END count: {0}.",e.BaseSettings.Count),SettingsTraceSwitch.Sw.Info);
		}
		#endregion

        #region overrides from SettingsDictionary
        
        public override void AddUpper(string key, SettingItem value)
        {
            if ( value.Type == SettingsType.Unknown )
                value.Type  =    SettingsType.Portal;
            Add(key.ToUpper(), value);
        }

        /// <summary>
        /// Uses the SettingItem.Key as key
        /// Force SettingItem.Type to Portal if Unknown
        /// </summary>
        public override void AddSetting(SettingItem value)
        {
            if ( value.Type == SettingsType.Unknown )
                value.Type  =    SettingsType.Portal;
            Add(value.Key, value);
        }

        #endregion overrides from SettingsDictionary

        public PortalSettingsDictionary GetPortalCustomSettings(int portalID)
		{
            if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings BEG portalID: {0}.",portalID),SettingsTraceSwitch.Sw.Info);
            string cachekey     =   Key2.PortalSettings;
            List<SettingItem> ApplyLst = CreateDependencyList();
            if ( Cache2.Exists(cachekey))
			{
                if ( SettingsTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings found in cache portalID: {0}, ApplyLst.Count: {1}.",portalID,ApplyLst.Count),SettingsTraceSwitch.Sw.Info);
                PortalSettingsDictionary result = (PortalSettingsDictionary)Cache2.Get(cachekey);
                if (result.Equals(this))
                {
                    if ( SettingsTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings END this = value in cache portalID: {0}, ApplyLst.Count: {1}.",portalID,ApplyLst.Count),SettingsTraceSwitch.Sw.Info);
                    return this;
                }
                for (int i = 0; i < ApplyLst.Count; i++)
                {
                    SettingItem st  =   ApplyLst[i];
                    st.Type         =   SettingsType.Portal;
                    st.ParentDBId   =   portalID;
                    if (result.ContainsKey(st.Key))
                    {
                        st.SetValueFromDB(result[st.Key].Value);
                        if (SettingsTraceSwitch.Sw.TraceVerbose)
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings key: {0} initialized.", st.Key), SettingsTraceSwitch.Sw.Info);
                    }
                }
                if ( SettingsTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings END loaded from cache portalID: {0}.",portalID),SettingsTraceSwitch.Sw.Info);
                return this;
			}

			// Get Settings for this Portal from the database
            PortalsDB PortalDB                  =   new PortalsDB();
            Dictionary<string, string> valDic   =   new Dictionary<string, string>();
			SqlDataReader dr			        =	null;
			try
			{
				dr						    =   PortalDB.GetPortalCustomSettings(portalID);
				while (dr.Read()) 
				{
                    string key              =   (string)dr[StStr.DBSettingName];
                    // nul content not allowed but string.empty allowed
                    object ob               =   dr[StStr.DBSettingValue];
                    if ( ob == DBNull.Value )
                        continue;
                    string val              =   ob.ToString();
                    string k                =   key.ToUpper();
                    if ( ContainsKey(k) &&
                        !val.Equals(this[k].Value) )
                    {
                         if ( SettingsTraceSwitch.Sw.TraceVerbose )
                             Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings {0}: replacing '{1}' by '{2}'", k,this[k].Value, val),SettingsTraceSwitch.Sw.Info);
                        this[k].Key    =   k;
                        valDic.Add(k, val);
                    }
                }
                if (SettingsTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings Inserting in cache portalID: {0}", portalID), SettingsTraceSwitch.Sw.Info);
			    CacheDependency settingDependencies = 
				    new CacheDependency(
                    new string[]{PortalSettings.webConfigPath},// add web config to this cache dependency
				    new string[]
						    {
							    Key2.PortalBaseSettings
						    });

			    using (settingDependencies)
			    {
				    Cache2.InsertLong(Key2.PortalSettings, this, settingDependencies);
			    }
                // if any, apply changes in order: items with dependencies fisrt
                if (valDic.Count > 0)
                {
                    for (int i = 0; i < ApplyLst.Count; i++)
                    {
                        SettingItem st = ApplyLst[i];
                        if (valDic.ContainsKey(st.Key))
                        {
                            st.SetValueFromDB(valDic[st.Key]);
                        }
                    }
                }
                Status = SettingsStatus.Loaded;
			}
			catch(Exception ex)
			{
				if ( SettingsTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PortalSettingsDictionary GetPortalCustomSettings PortalID: {0}, ex: {1}",portalID,ex),SettingsTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( dr != null && !dr.IsClosed )
					dr.Close();
			}

            if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PortalSettingsDictionary GetPortalCustomSettings END loaded from DB portalID: {0}.",portalID),SettingsTraceSwitch.Sw.Info);
			return this;
		}

    }

}
